#include <stdio.h>
#include <stdlib.h>

//结点
typedef struct _NODE
{
    int data;
    struct _NODE *pre;
    struct _NODE *next;
} NODE;

//初始化
bool InitList(NODE *&L)
{

    if (L != nullptr)
        return false;

    L = (NODE *)malloc(sizeof(NODE));
    if (L)
    {
        L->next = nullptr;
        L->pre = nullptr;
        return true;
    }
    return false;
}

//加入数据
void list_add(NODE *&L, int i, int x)
{
    NODE *p = nullptr;

    if (!InitList(p))
        return;
    p->data = x;

    if (i == 1)
    {
        p->next = L;
        L->pre = p;
        L = p;
    }
    else
    {

        NODE *head = L;
        while (--i && head->next)
        {

            head = head->next;
        }

        //插入位置
        if (head->next)
        {

            head->next->pre = p;
            p->next = head->next;
            p->pre = head;
            head->next = p;
        }
        else
        {

            head->next = p;
            p->pre = head;
        }
    }
}

//删除数据
void list_del(NODE *&L, int x)
{
    NODE *p = L;

    while (p->data != x && p)
    {
        if (!p->next)
        {
            break;
        }
        else
        {
            p = p->next;
        };
    }

    if (p->next)
    {
        p->pre->next = p->next;
        p->next->pre = p->pre;
        free(p);
    }
    else
    {
        //是否是尾部数据
        if (p->data == x)
        {
            p->pre->next = p->next;
        }
        else
        {
            printf("not find\n");
        }
    }
}

//替换数据
void list_rep(NODE *&L, int x, int k)
{
    NODE *p = nullptr;
    p = L->next;

    while (p->data != x && p)
    {
        if (!p->next)
        {
            break;
        }
        else
        {
            p = p->next;
        }
    }

    if (p->next)
    {
        p->data = k;
    }
    else
    {
        if (p->data == x)
            p->data = k;
    }
}

//便利输出单链表
void print_list(NODE *L)
{
    NODE *p = L->next;
    int i = 0;
    printf("=================\n");

    while (p)
    {
        printf("number %d value :%d\n", ++i, p->data);

        if (!p->next)
        {
            break;
        }
        else
        {
            p = p->next;
        }
    }

    printf("---------------\n");

    while (p->pre)
    {
        printf("number %d value :%d\n", --i, p->data);
        p = p->pre;
    }
}

int main()
{
    NODE *head = nullptr;

    if (!InitList(head))
        return 0;

    list_add(head, 1, 1);
    // print_list(head);
    list_add(head, 2, 2);
    // print_list(head);
    list_add(head, 2, 3);
    print_list(head);
    list_rep(head, 4, 6);
    print_list(head);
    list_del(head, 2);
    list_del(head, 4);
    print_list(head);

    return 0;
}